package com.etop.weiway.wxmanage.service;

import com.etop.weiway.basic.service.BaseService;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.dao.*;
import com.etop.weiway.wxmanage.entity.Account;
import com.etop.weiway.wxmanage.entity.User;
import com.etop.weiway.wxmanage.util.WeixinTimeUtil;
import com.etop.weixin.entity.common.AccessToken;
import com.etop.weixin.utils.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 公众号管理服务类
 * Created by Jeremie on 2014/12/11.
 */
@Service("AccountService")
public class AccountService extends BaseService {

    @Autowired
    private AccountDAO accountDAO;
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private WeixinMenuDAO weixinMenuDAO;
    @Autowired
    private MassDAO massDAO;
    @Autowired
    private AutoReplyDAO autoReplyDAO;
    @Autowired
    private MaterialTextDAO materialTextDAO;
    @Autowired
    private MaterialNewsDAO materialNewsDAO;
    @Autowired
    private MaterialMutinewsDAO materialMutinewsDAO;
    @Autowired
    private MaterialVideoDAO materialVideoDAO;
    @Autowired
    private MaterialVoiceDAO materialVoiceDAO;
    @Autowired
    private MaterialImageDAO materialImageDAO;

    /**
     * 校验用户所填写的appId和appSecret的正确性，如果是正确的，则理应可以获取到accessToken
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public boolean checkGetAccessToken(String appId, String appSecret) throws Exception {
        log.debug("*********************校验用户所填写的appId和appSecret的正确性***********************");
        AccessToken accessToken = WeixinUtil.getAccessToken(appId, appSecret);
        if (accessToken == null) {
            log.info("appId:" + appId + "和appSecret:" + appSecret + ",不能获取到accessToken !");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 使用id获得公众号
     *
     * @param id
     * @return
     */
    public Account loadAccount(int id) {
        log.debug("******根据id查询公众号******");
        Map<String, Object> params = createParamMap();
        params.put("id", id);
        String queryString = "from Account t where t.valid = 1 and id =:id";
        return accountDAO.findUniqueResult(queryString, params);
    }

    /**
     * 使用wechatId获得公众号
     *
     * @param wechatId
     * @return
     */
    public Account loadAccountByWechatId(String wechatId) throws Exception {
        log.debug("******根据wechatId查询公众号******");
        Map<String, Object> params = createParamMap();
        params.put("wechatId", wechatId);
        String queryString = "from Account t where t.valid = 1 and wechatId =:wechatId";
        return accountDAO.findUniqueResult(queryString, params);
    }


    /**
     * 保存或更新公众号
     *
     * @param account
     */
    public Account saveAccount(Account account, boolean FirstAccount) throws Exception {
        log.debug("******保存或更新公众号******");
        log.info("--------------------------->" + account.getName());
        account.setTokenCreatedTime(0l);
        accountDAO.saveOrUpdate(account);
        if (FirstAccount) {
            Map<String, Object> map = this.createParamMap();
            map.put("id", account.getUser().getId());
            User user = userDAO.findUniqueResult("from User t where t.id = :id", map);
            user.setCurrentAccount(account);
            userDAO.update(user);
        }
        return account;
    }

    /**
     * 根据id删除公众号(假删除)(返回下一个公众号,若有当前公众号，则不删除)
     *
     * @param id
     * @param currentId
     */
    public Account deleteAccountById(int id, boolean currentId) throws Exception {
        log.debug("******根据id删除公众号******");
        Account returnAccount = null;
        if (currentId) {
            //修改user对应的currentAccount
            Map<String, Object> map = this.createParamMap();
            map.put("id", id);
            String queryString = "from User t where t.valid = 1 and t.currentAccount.id = :id";
            User user = userDAO.findUniqueResult(queryString, map);
            //如果还有其他公众号，将最先的设为当前公众号,否则为null
            String queryString2 = "from Account t where t.valid = 1 and t.user.id = :userId";
            Map<String, Object> params = this.createParamMap();
            params.put("userId", user.getId());
            queryString2 += " order by t.id desc";
            List<Account> accounts = accountDAO.find(queryString2, params);
            user.setCurrentAccount(null);
            if (accounts != null)
                for (Account account : accounts)
                    if (account.getId() != id) {
                        returnAccount = account;
                        user.setCurrentAccount(returnAccount);
                        break;
                    }
            userDAO.update(user);
        }
        Account account = new Account();
        account.setId(id);
        accountDAO.invalid(account);
        //删除对应公众号的素材资源，菜单和自动回复
        Map<String, Object> map = this.createParamMap();
        map.put("accountId", id);
        weixinMenuDAO.excute("update WeixinMenu t set t.valid = 0 where t.account.id = :accountId", map);
        massDAO.excute("update Mass t set t.valid = 0 where t.account.id = :accountId", map);
        autoReplyDAO.excute("update AutoReply t set t.valid = 0 where t.account.id = :accountId", map);
        materialTextDAO.excute("update MaterialText t set t.valid = 0 where t.account.id = :accountId", map);
        materialNewsDAO.excute("update MaterialNews t set t.valid = 0 where t.account.id = :accountId", map);
        materialMutinewsDAO.excute("update MaterialMutinews t set t.valid = 0 where t.account.id = :accountId", map);
        materialVideoDAO.excute("update MaterialVideo t set t.valid = 0 where t.account.id = :accountId", map);
        materialVoiceDAO.excute("update MaterialVoice t set t.valid = 0 where t.account.id = :accountId", map);
        materialImageDAO.excute("update MaterialImage t set t.valid = 0 where t.account.id = :accountId", map);
        return returnAccount;
    }

    /**
     * 分页查询公众号
     *
     * @param pager
     * @return pager<News>
     * @throws Exception
     * @Pager keyword
     */
    public Pager<Account> getAccountByPage(Pager<Account> pager, String keyword, int userId) throws Exception {
        log.debug("******根据条件查询公众号******");
        Map<String, Object> params = createParamMap();
        String queryString = "from Account t where t.valid = 1 and t.user.id = :userId";
        params.put("userId", userId);
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.name like :keyword )";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.id desc";
        List<Account> accounts = accountDAO.find(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(accountDAO.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    /**
     * 选择当前公众号
     *
     * @param accountId
     * @param userId
     */
    public void saveCurrentAccount(int accountId, int userId) throws Exception {
        log.debug("******选择当前公众号******");
        User user = userDAO.get(userId);
        user.setCurrentAccount(accountDAO.get(accountId));
        userDAO.saveOrUpdate(user);
    }

    /**
     * 保存头像
     *
     * @param path
     * @param file
     * @return
     */
    public String savePortrait(String path, MultipartFile file) throws Exception {
        log.debug("******保存头像******");
        String fileName = super.uploadMedia(file, path, "image");
        return fileName;
    }

}
